package com.youga.imageselector.util;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.content.ContextCompat;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by Youga on 2016/1/6.
 */
public class PermissionUtil {

    public static boolean mayWriteExternalStorage(Activity activity, int requestCode,
                                                  PermissionCallBack callBack) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (activity.shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
            callBack.shouldShowAlertDialog("需要打开SD卡读写权限才能拍照");
        } else {
            activity.requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE}, requestCode);
        }
        return false;
    }


    public static boolean mayCamera(Activity activity, int requestCode,
                                    PermissionCallBack callBack) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (ContextCompat.checkSelfPermission(activity, CAMERA) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (activity.shouldShowRequestPermissionRationale(CAMERA)) {
            callBack.shouldShowAlertDialog("需要打开相机才能拍照");
        } else {
            activity.requestPermissions(new String[]{CAMERA}, requestCode);
        }
        return false;
    }

    public interface PermissionCallBack{
        void shouldShowAlertDialog(String title);
    }
}
